<?php
namespace control;

/*
*个税核算类
*/

class personalTaxClass extends adIndexClass
{
    private const title = '个税核算';
    private const page = 'personalTax';
    private const table = 'personal_tax';

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        if ($workFlow == '个税记录') {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]) .
                text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => L('salary.table.jiao_na_yue_fen')));
        } else {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]);
        }

        return $this->search($html, 'menu');
    }

    /**
     * 设备扣款
     *
     */
    public function deduction()
    {
        $json['html'] = $this->homeForm('个税扣款');
        return json_encode($json, 320);
    }

    public function deductionSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = " and isCommit = 0";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $timeArr = explode('~', $this->post('moon'));
            $and .= " and month >='{$timeArr[0]}' and month <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 500, "order" => " month desc,id desc"));
        //获取表头
        $checkAll = $this->checkAll("recordForm", "recordId");
        $tr[] = array($checkAll, L('salary.table.bu_men'), L('salary.table.zhi_wei'), L('salary.table.yuan_gong'), L('salary.table.gskk') . '(' . static::$unit . ')', L('salary.table.bei_zhu'));
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "recordId", "value" => $array['id']),
            );
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            //数据库查询
            $staff = query("staff", " stid = '$array[staffId]' ");
            $decText = text(array('name' => "decMoney[$array[id]]", 'class' => 'text textPrice', 'value' => $array['tax']));
            $text = text(array('name' => "text[$array[id]]", 'class' => 'text textPrice', 'value' => ''));
            //本行
            $tr[] = array($this->dominate($dominate), $department['name'], $job['name'], $staff['name'], $decText, $text);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'commitDec', {})\">" . L('clock.table.decMoney') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='recordForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 提交扣款
     * @return bool|string
     */
    public function commitDec()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') => L('salary.table.tax_warn'),
            ),
        ), 'formTwo' => 'recordForm'));
        //返回
        return $this->layer(array("title" => L('salary.table.gskk'), "height" => 160, "width" => 600, "html" => $html));
    }

    /**
     * 账户扣款编辑
     * @return bool|string
     */
    public function commitDecEdit()
    {
        $listId = $this->post('recordId');
        $textArr = $this->post('text');
        $decMoneyArr = $this->post('decMoney');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.tax_edit_permission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        } else {
            $x = 0;
            foreach ($listId as $k => $id) {
                $info = query(self::table, " id = '$id'");
                $staff = query('staff', " stid = '$info[staffId]'");
                $warn = update(array(
                    "table" => self::table,
                    "field" => [
                        'decMoney' => $decMoneyArr[$id],
                        'text' => $textArr[$id],
                        'stid' => $this->control['stid'],
                        'isCommit' => 1,
                    ],
                    'where' => " id = '$id'"
                ));
                if ($warn == '更新成功') {
                    $x++;
                    //添加日志
                    $text = str_replace(['{{staffName}}', '{{name}}', '{{month}}'], [$this->control['name'], $staff['name'], $info['month']], L('salary.table.tax_commit_log'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary_table.tax_commit_text'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&menu=deduction&id=all";
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 查询条件
     *
     * @param string $workFlow
     * @return string
     */
    public function home($workFlow = '个税记录'): string
    {
        if ($workFlow == '个税记录') {
            $data = [
                "id" => "all",
                "menu" => [
                    "record" => L('salary.table.ge_shui_ji_lu'),
                    "deduction" => L('salary.table.gskk'),
                ]
            ];
        }
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $timeArr = explode('~', $this->post('moon'));
            $and .= " and moon >='{$timeArr[0]}' and moon <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy') ?? null,
            "default" => '缴款月份',
            "array" => array(
                "month" => array("desc" => '缴款月份', "site" => 5),
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('salary.table.bu_men'), L('salary.table.zhi_wei'), L('salary.table.yuan_gong'), L('salary.table.jiao_na_yue_fen'), "个税(". static::$unit . ")");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            //数据库查询
            $staff = query("staff", " stid = '$array[staffId]' ");
            //本行
            $tr[] = array($this->dominate($dominate), $department['name'], $job['name'], $staff['name'], $array['month'], $array['tax']);
        }
        //控件
        $button = "";
        //导入
        if ($this->power("insure", "edit")) {
            $button .=
                importTemplateClass::importTemplateButton(self::page) .
                $this->upButton(array("title" => L('salary.table.importTax'), "fun" => "importData"));
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr, "orderBySign" => $orderBy)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('salary.table.nhmzbjdzx');
        } else {
            $title = [L('salary.table.xing_ming'), L('salary.table.idCard'), L('salary.table.jiao_na_yue_fen'), L('salary.table.ge_shui')];
            $data[] = ['张三', '500223199510111111', '202101', 100, '样例数据，导入时请删除本条数据'];
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.tax_template'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('salary.table.tax_template_title') . '.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入分析-个税*/
    public function importData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('salary.table.nhmzbjdzx');
        } else {

            $data = $this->importHead();
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $IDCard = $cell[1];//身份证号码
                    $talent = query('talent_pool', " idCard = '$IDCard'");
                    $staff = query("staff", "talentId = '$talent[id]'");
                    $moon = date('Y-m', strtotime($cell[2] . '01'));
                    $field = array(
                        "id" => self::getId(),
                        "staffId" => $staff['stid'],//员工ID
                        'jobId' => $staff['jobId'],
                        "month" => $moon,//缴款月份
                        "tax" => $cell[3],//个税
                    );
                    $line = str_replace(['{{i}}'], [$i], L('job.other.line'));
                    if (empty($field['staffId']) || !$talent['id']) {
                        $text .= $line . "：" . L('salary.table.find_no_staff') . "\n";
                    } elseif (sqlNum(self::table, "staffId = '$staff[stid]'  and month = '$moon' ") > 0) {
                        $text .= $line . ":" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.exist_data'));
                    } else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= $line . "：" . L('job.other.import_success') . "<br>";
                        } else {
                            $text .= $line . "：" . L('job.other.import_failed') . "<br>";
                        }
                    }
                }
            }
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.taxDel');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = L('salary.table.sccg');
                $x++;
                $text .= str_replace(['{{name}}', '{{month}}'], [self::findStaff($info['staffId']), $info['month']], L('salary.table.tax_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.tax_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.tax_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
